package com.shijiwei.lifthelper.fragment;

import android.content.Intent;
import android.graphics.drawable.AnimationDrawable;
import android.os.Bundle;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Toast;

import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.shijiwei.lifthelper.R;
import com.shijiwei.lifthelper.adapter.JokeAdapter;
import com.shijiwei.lifthelper.bean.JokeBean;
import com.shijiwei.lifthelper.ui.JokeInfoActivity;
import com.shijiwei.lifthelper.utils.UrlConstants;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.common.Callback;
import org.xutils.common.util.LogUtil;
import org.xutils.http.RequestParams;
import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.ViewInject;
import org.xutils.x;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by sjw on 2015/12/12.
 */
@ContentView(R.layout.fragment_joke)
public class  JokeFragment extends BaseFragment {

    @ViewInject(R.id.layout_loading_joke)
    private FrameLayout loadingLayout;
    @ViewInject(R.id.ptrlv_joke)
    private PullToRefreshListView jokePtrListView;
    @ViewInject(R.id.iv_joke_back_top)
    private ImageView backToTopImage;

    private JokeAdapter jokeAdapter;
    private List<JokeBean> jokeBeans = new ArrayList<>();

    private int page = 1;
    private Callback.Cancelable get;

    // 声明一个动画
    private AnimationDrawable drawable;

    public static JokeFragment newInstance() {
        JokeFragment fragment = new JokeFragment();
        return fragment;
    }
    @Override
    public void initView() {
        ImageView iv = (ImageView) loadingLayout.findViewById(R.id.iv_loading);
        if (iv.getBackground() instanceof AnimationDrawable) {
            drawable = (AnimationDrawable) iv.getBackground();
        }
        if (drawable != null) {
            drawable.start();
        }

        jokeAdapter = new JokeAdapter(jokeBeans ,getActivity());
        jokePtrListView.setAdapter(jokeAdapter);

        jokePtrListView.setMode(PullToRefreshBase.Mode.BOTH);
        jokePtrListView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
                LogUtil.e("-----下拉刷新");
                page = 1;
                x.http().get(getRequestParams(14), new Callback.CommonCallback<String>() {
                    @Override
                    public void onSuccess(String result) {
                        if (result == null) {
                            Toast.makeText(getActivity(), "当前没有更新", Toast.LENGTH_SHORT).show();
                        } else {
                            jokeBeans.clear();
                            try {
                                JSONObject object = new JSONObject(result);
                                JSONArray array = object.getJSONArray("items");
                                for (int i = 0; i < array.length(); i++) {
                                    JSONObject obj = array.getJSONObject(i);
                                    JokeBean joke = com.alibaba.fastjson.JSONObject.parseObject(obj.toString(), JokeBean.class);
                                    jokeBeans.add(joke);
                                }
                                jokeAdapter.notifyDataSetChanged();
                                jokePtrListView.onRefreshComplete();
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                    }

                    @Override
                    public void onError(Throwable ex, boolean isOnCallback) {
                        Toast.makeText(getActivity(), "亲，网络异常，加载不出来啊", Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onCancelled(CancelledException cex) {
                    }

                    @Override
                    public void onFinished() {
                    }
                });

            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
                page++;
                x.http().get(getRequestParams(15), new Callback.CommonCallback<String>() {
                    @Override
                    public void onSuccess(String result) {
                        LogUtil.e("-----上拉刷新");
                        if (result == null) {
                            Toast.makeText(getActivity(), "当前没有更新", Toast.LENGTH_SHORT).show();
                        } else {
                            try {
                                JSONObject object = new JSONObject(result);
                                JSONArray array = object.getJSONArray("items");
                                for (int i = 0; i < array.length(); i++) {
                                    JSONObject obj = array.getJSONObject(i);
                                    JokeBean joke = com.alibaba.fastjson.JSONObject.parseObject(obj.toString(), JokeBean.class);
                                    jokeBeans.add(joke);
                                }
                                jokeAdapter.notifyDataSetChanged();
                                jokePtrListView.onRefreshComplete();
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                    }

                    @Override
                    public void onError(Throwable ex, boolean isOnCallback) {
                        Toast.makeText(getActivity(), "亲，网络异常，加载不出来啊", Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onCancelled(CancelledException cex) {
                    }

                    @Override
                    public void onFinished() {
                    }
                });

            }
        });

        jokePtrListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent = new Intent(getActivity(), JokeInfoActivity.class);
                intent.putExtra("joke", jokeBeans.get(position - 1));
                startActivity(intent);
            }
        });

        jokePtrListView.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {
            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
                if (firstVisibleItem > 3) {
                    backToTopImage.setVisibility(View.VISIBLE);
                } else if (firstVisibleItem == 0){
                    backToTopImage.setVisibility(View.GONE);
                }
            }
        });

        backToTopImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                jokePtrListView.getRefreshableView().setSelection(0);
            }
        });
    }

    @Override
    public void initData() {
        backToTopImage.setVisibility(View.GONE);
        get = x.http().get(new RequestParams("http://mobileapi1.roboo.com/joke/textJokeJson.do?p=1&ps=14"), new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                LogUtil.e("-------Joke"+result);
                if (result == null) {
                    Toast.makeText(getActivity(), "受未知力量的影响，当前数据无法加载！！", Toast.LENGTH_SHORT).show();
                } else {
                    try {
                        JSONObject object = new JSONObject(result);
                        JSONArray array = object.getJSONArray("items");
                        for (int i = 0; i < array.length(); i++) {
                            JSONObject obj = array.getJSONObject(i);
                            JokeBean joke = com.alibaba.fastjson.JSONObject.parseObject(obj.toString(), JokeBean.class);
                            jokeBeans.add(joke);
                        }
                        jokeAdapter.notifyDataSetChanged();
                        loadingLayout.setVisibility(View.GONE);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                Toast.makeText(getActivity(), "亲，网络异常，加载不出来啊", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onCancelled(CancelledException cex) {}

            @Override
            public void onFinished() {}
        });

    }

    /**
     * 初始化 RequestParams
     * @param ps 每页的数据量
     * @return
     */
    private RequestParams getRequestParams(int ps){
        RequestParams params = new RequestParams(UrlConstants.JOKE_URL_GET);
        params.addBodyParameter("p",page+"");
        params.addBodyParameter("ps",ps+"");
        return params;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (get != null){
            get.cancel();
        }

        if (drawable != null){
            drawable.stop();
        }
    }
}
